package com.dawnling.countdownlistdemo.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import com.dawnling.countdownlistdemo.utils.MyTimer;

public class MyApplication extends Application {

    protected Handler mHandler;
    protected MyTimer mTimer;
    protected Context mContext;
    private static MyApplication instance;

    public static synchronized MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mContext = this;
        mHandler = new Handler();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            private int count;
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                count++;
                if (mTimer != null) {
                    mTimer.onStart();
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                count--;
                if (count == 0 && mTimer != null) {
                    mTimer.onStop();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    public MyTimer getTimer() {
        if (mTimer == null) {
            if (mHandler == null) {
                mHandler = new Handler();
            }
            mTimer = new MyTimer(mHandler);
        }
        return mTimer;
    }
}
